package com.trytech.mongoocrawler.client.common.util;

import com.trytech.mongoocrawler.client.transport.http.CrawlHttpUrlParam;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by hp on 2017-1-24.
 */
public class HttpUtils {
    private final static HttpClient httpClient = new DefaultHttpClient();
    public static List<? extends NameValuePair> paramFromMap(Map<String, Object> params){
        List paramList = new LinkedList();
        if(params != null) {
            for (String key : params.keySet()) {
                CrawlHttpUrlParam param = new CrawlHttpUrlParam(key, (String) params.get(key));
                paramList.add(param);
            }
        }
        return paramList;
    }
    public static String get(String url){
        try {
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);
            if(response.getStatusLine().getStatusCode() == 200){
                return EntityUtils.toString(response.getEntity(),"utf-8");
            }
        }catch (Exception e){

        }
        return null;
    }
    public static String post(String url, Map params){
        try {
            HttpPost post = new HttpPost(url);
            if(params != null) {
                post.setEntity(new UrlEncodedFormEntity(getParamsFromMap(params), HTTP.UTF_8));
            }
            HttpResponse response = httpClient.execute(post);
            if(response.getStatusLine().getStatusCode() == 200){
                return EntityUtils.toString(response.getEntity(),"utf-8");
            }
        }catch (Exception e){

        }
        return null;
    }

    private static List<NameValuePair> getParamsFromMap(Map params){
        List<NameValuePair> result = new ArrayList<NameValuePair>();
        params.entrySet().iterator();
        for(Iterator ite = params.entrySet().iterator();ite.hasNext();){
            Map.Entry entry = (Map.Entry)ite.next();
            result.add(new BasicNameValuePair(entry.getKey().toString(),entry.getValue().toString()));
        }
        return result;
    }
}
